<?php
namespace SimplePHp\Rendering;

/**
 *
 */
class ElementResovle {
	//页面对象
	//转换元素
	private $html, $elementList = [];
	public function __construct($file, $elementList = []) {
		if (!is_file($file)) {
			throw new \Exception("模板文件不存在", 1);
		}
		$this->html = new \DOMDocument();
		$this->html->load($file);
		$this->elementList = [
			new ForElement(),
			new EchoElement(),
		];
		$this->elementList = array_merge($this->elementList, $elementList);
		//通过level进行标签排序
		$this->sortElement($this->elementList);
		$this->init();
	}
	/**
	 * 初始化解析标签列表
	 * @return [type] [description]
	 */
	private function init() {
		foreach ($this->elementList as $key => $value) {
			$Elementlist = $this->html->getElementsByTagName($value->getTagName());
			$Elementlist = new DOMNodeListIterator($Elementlist);
			foreach ($Elementlist as $key_ => $value_) {
				$value->trunPhp($this->html, $value_);
			}
		}
	}
	private function sortElement(&$arr) {
		usort($arr, function ($a, $b) {
			$a = $a->getLevel();
			$b = $b->getLevel();
			if ($a == $b) {
				return 0;
			}
			return ($a < $b) ? -1 : 1;
		});
	}
	/**
	 * 获取生成的php缓存页面
	 * @return [type] [description]
	 */
	public function getHtml() {
		$content = htmlspecialchars_decode($this->html->saveHTML());
		//使用正则表达式替换量化模板
		//闭合标签
		$content = preg_replace_callback("/<php[\s]+phpCode=\"(.+)\"[\s]{0,}>/", function ($match) {
			return "<?php $match[1] ?>";
		}, $content);
		//单标签
		$content = preg_replace_callback("/<php_open[\s]+phpCode=\"(.+)\"[\s]{0,}>/", function ($match) {
			return "<?php $match[1] ?>";
		}, $content);
		$content = str_replace(["</php>", "</php_open>"], ["<?php } ?>", ""], $content);
		return $content;
	}
}